<template>
  <div class="virtual-list">
    <div
      scroll-y="true"
      :style="{
        height: ' 100%',
        position: 'relative',
      }"
      @scroll="handleScroll"
    >
      <div
        class="scroll-bar"
        :style="{
          height: localHeight + 'px',
        }"
      />
      <div
        class="list"
        :style="{
          transform: `translateY(${offset}px)`,
        }"
      >
        <div v-for="(item, index) in visibleData" :key="index" class="" style="width: 100%">
          <slot :data="{ item, index }" name="slotItem"></slot>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'VirtualList',
    props: {
      // 所有的items
      items: {
        type: Array,
        default: function () {
          return []
        },
      },
      // 可视区域的item数量
      remain: {
        type: Number,
        default: 0,
      },
      // item大小
      size: {
        type: Number,
        default: 0,
      },
    },
    data() {
      return {
        // 起始
        start: 0,
        // 结束
        end: this.remain,
        // list 偏移量
        offset: 0,
      }
    },
    computed: {
      // 预留项
      preCount() {
        return Math.min(this.start, this.remain)
      },
      nextCount() {
        return Math.min(this.items.length - this.end, this.remain)
      },
      // 可视区域的item
      visibleData() {
        const start = this.start - this.preCount
        const end = this.end + this.nextCount
        console.log('this.items.slice(start, end)', this.items.slice(start, end))
        return this.items.slice(start, end)
      },
      scrollHeight() {
        return this.remain * this.size
      },
      localHeight() {
        // return this.items.length * this.size
        return this.items.length
      },
    },

    methods: {
      handleScroll(ev) {
        const scrollTop = ev.detail.scrollTop
        // 开始位置
        const start = Math.floor(scrollTop / this.size)
        this.start = start < 0 ? 0 : start
        // 结束位置
        this.end = this.start + this.remain
        // 计算偏移
        const offset = scrollTop - (scrollTop % this.size) - this.preCount * this.size
        this.offset = offset < 0 ? 0 : offset
      },
    },
  }
</script>

<style scoped lang="scss">
  .list {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    // height: 100%;
    flex-wrap: wrap;
    overflow: none;
    // > div {
    //   height: 100%;
    // }
  }
</style>
